package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysWater;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserWater;
import com.ruoyi.system.service.ISysAerationService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysWaterService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 水泵机信息
 *
 * @author xiongdong
 */
@RestController
@RequestMapping("/system/water")
public class SysWaterController extends BaseController
{

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysAerationService aerationService;
    
    @Autowired
    private ISysWaterService waterService;

    @PreAuthorize("@ss.hasPermi('system:water:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysWater sysWater)
    {
        startPage();
        List<SysWater> list = waterService.selectSysWaterList(sysWater);
        return getDataTable(list);
    }

    @Log(title = "水泵机管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:water:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysWater sysWater)
    {
        List<SysWater> list = waterService.selectSysWaterList(sysWater);
        ExcelUtil<SysWater> util = new ExcelUtil<SysWater>(SysWater.class);
        util.exportExcel(response, list, "水泵机数据");
    }

    /**
     * 根据水泵机编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:water:query')")
    @GetMapping(value = "/{waterId}")
    public AjaxResult getInfo(@PathVariable Long waterId)
    {
        waterService.checkWaterDataScope(waterId);
        return success(waterService.selectWaterById(waterId));
    }

    /**
     * 新增水泵机
     */
    @PreAuthorize("@ss.hasPermi('system:water:add')")
    @Log(title = "水泵机管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysWater sysWater)
    {
        if (UserConstants.NOT_UNIQUE.equals(waterService.checkWaterNameUnique(sysWater)))
        {
            return error("新增水泵机'" + sysWater.getWaterName() + "'失败，水泵机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(waterService.checkWaterKeyUnique(sysWater)))
        {
            return error("新增水泵机'" + sysWater.getWaterName() + "'失败，水泵机权限已存在");
        }
        sysWater.setCreateBy(getUsername());
        return toAjax(waterService.insertWater(sysWater));

    }

    /**
     * 修改保存水泵机
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysWater sysWater)
    {
        waterService.checkWaterAllowed(sysWater);
        waterService.checkWaterDataScope(sysWater.getWaterId());
        if (UserConstants.NOT_UNIQUE.equals(waterService.checkWaterNameUnique(sysWater)))
        {
            return error("修改水泵机'" + sysWater.getWaterName() + "'失败，水泵机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(waterService.checkWaterKeyUnique(sysWater)))
        {
            return error("修改水泵机'" + sysWater.getWaterName() + "'失败，水泵机权限已存在");
        }
        sysWater.setUpdateBy(getUsername());

        if (waterService.updateWater(sysWater) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改水泵机'" + sysWater.getWaterName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysWater sysWater)
    {
        waterService.checkWaterAllowed(sysWater);
        waterService.checkWaterDataScope(sysWater.getWaterId());
        return toAjax(waterService.authDataScope(sysWater));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysWater sysWater)
    {
        waterService.checkWaterAllowed(sysWater);
        waterService.checkWaterDataScope(sysWater.getWaterId());
        sysWater.setUpdateBy(getUsername());
        return toAjax(waterService.updateWaterStatus(sysWater));
    }

    /**
     * 删除水泵机
     */
    @PreAuthorize("@ss.hasPermi('system:water:remove')")
    @Log(title = "水泵机管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{waterIds}")
    public AjaxResult remove(@PathVariable Long[] waterIds)
    {
        return toAjax(waterService.deleteWaterByIds(waterIds));
    }

    /**
     * 获取水泵机选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:water:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(waterService.selectWaterAll());
    }

    /**
     * 查询已分配用户水泵机列表
     */
    @PreAuthorize("@ss.hasPermi('system:water:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList2(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户水泵机列表
     */
    @PreAuthorize("@ss.hasPermi('system:water:list')")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList2(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserWater userWater)
    {
        return toAjax(waterService.deleteUserWater(userWater));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long waterId, Long[] userIds)
    {
        return toAjax(waterService.deleteDeptWaters(waterId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:water:edit')")
    @Log(title = "水泵机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long waterId, Long[] userIds)
    {
        waterService.checkWaterDataScope(waterId);
        return toAjax(waterService.insertDeptWaters(waterId, userIds));
    }

    /**
     * 获取对应水泵机渔场树列表
     */
    @PreAuthorize("@ss.hasPermi('system:water:query')")
    @GetMapping(value = "/deptTree/{waterId}")
    public AjaxResult deptTree(@PathVariable("waterId") Long waterId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByWaterId(waterId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
